<script setup lang="tsx">
import { computed, ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag, NTree } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import {
  fetchBatchDeleteMenu,
  fetchGetAllMenus,
  fetchGetAllPages,
  fetchGetMenuDetail,
  fetchGetMenuList
} from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { yesOrNoRecord } from '@/constants/common';
import { enableStatusRecord, menuTypeRecord } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import MenuOperateModal from './modules/menu-operate-modal.vue';
import type { OperateType } from './modules/menu-operate-modal';

const appStore = useAppStore();

const { bool: visible, setTrue: openModal } = useBoolean();

// Tree menu
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const searchKeyword = ref('');
const rawTreeData = ref<Api.SystemManage.Menu[]>([]);

const wrapperRef = ref<HTMLElement | null>(null);

// 获取树状菜单数据
async function getTreeData() {
  const { data } = await fetchGetAllMenus();
  rawTreeData.value = data || [];
}

const { columns, columnChecks, data, loading, pagination, getData, getDataByPage, searchParams } = useTable({
  apiFn: fetchGetMenuList,
  apiParams: {
    current: 1,
    size: 10,
    parentId: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: $t('page.manage.menu.id'),
      align: 'center'
    },
    {
      key: 'menuType',
      title: $t('page.manage.menu.menuType'),
      align: 'center',
      width: 80,
      render: row => {
        const tagMap: Record<Api.SystemManage.MenuType, NaiveUI.ThemeColor> = {
          1: 'default',
          2: 'primary',
          3: 'warning'
        };

        const label = $t(menuTypeRecord[row.menuType]);

        return <NTag type={tagMap[row.menuType]}>{label}</NTag>;
      }
    },
    {
      key: 'menuName',
      title: $t('page.manage.menu.menuName'),
      align: 'center',
      minWidth: 120,
      render: row => {
        const { i18nKey, menuName } = row;

        const label = i18nKey ? $t(i18nKey) : menuName;

        return <span>{label}</span>;
      }
    },
    {
      key: 'icon',
      title: $t('page.manage.menu.icon'),
      align: 'center',
      width: 60,
      render: row => {
        const icon = row.iconType === '1' ? row.icon : undefined;

        const localIcon = row.iconType === '2' ? row.icon : undefined;

        return (
          <div class="flex-center">
            <SvgIcon icon={icon} localIcon={localIcon} class="text-icon" />
          </div>
        );
      }
    },
    {
      key: 'routeName',
      title: $t('page.manage.menu.routeName'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'permissions',
      title: '权限',
      align: 'center',
      minWidth: 50
    },
    {
      key: 'routePath',
      title: $t('page.manage.menu.routePath'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: $t('page.manage.menu.menuStatus'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'hideInMenu',
      title: $t('page.manage.menu.hideInMenu'),
      align: 'center',
      width: 80,
      render: row => {
        const hide: CommonType.YesOrNo = row.hideInMenu ? 'Y' : 'N';

        const tagMap: Record<CommonType.YesOrNo, NaiveUI.ThemeColor> = {
          Y: 'error',
          N: 'default'
        };

        const label = $t(yesOrNoRecord[hide]);

        return <NTag type={tagMap[hide]}>{label}</NTag>;
      }
    },
    {
      key: 'parentId',
      title: $t('page.manage.menu.parentId'),
      width: 90,
      align: 'center'
    },
    {
      key: 'order',
      title: $t('page.manage.menu.order'),
      align: 'center',
      width: 60
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 230,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {row.menuType !== '3' && (
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildMenu(row)}>
              {$t('page.manage.menu.addChildMenu')}
            </NButton>
          )}
          <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const treeData = computed(() => {
  return rawTreeData.value.map(menu => {
    // 确保每个节点都包含完整菜单数据
    const menuNode = {
      key: menu.id.toString(),
      label: menu.menuName,
      icon: menu.icon,
      iconType: menu.iconType,
      menuItem: menu, // 添加完整菜单数据
      children:
        menu.children?.map(child => ({
          key: child.id.toString(),
          label: child.menuName,
          icon: child.icon,
          iconType: child.iconType,
          menuItem: child // 子菜单也添加完整数据
        })) || []
    };
    return menuNode;
  });
});

const renderPrefix = ({ option }: { option: any }) => {
  if (!option.icon) return null;

  return option.iconType === '2' ? (
    <SvgIcon localIcon={option.icon} class="mr-1 text-icon" />
  ) : (
    <SvgIcon icon={option.icon} class="mr-1 text-icon" />
  );
};

const renderSuffix = ({ option }: { option: any }) => {
  // 直接从option中获取完整菜单项数据
  const menuItem = option.menuItem;
  if (!menuItem) return null;

  return (
    <div class="flex gap-1">
      <NButton size="tiny" type="primary" onClick={() => handleAddChildMenu(menuItem)}>
        添加
      </NButton>
      <NButton size="tiny" type="info" onClick={() => handleEdit(menuItem)}>
        修改
      </NButton>
      <NPopconfirm onPositiveClick={() => handleDelete(menuItem.id)}>
        {{
          default: () => $t('common.confirmDelete'),
          trigger: () => (
            <NButton size="tiny" type="error">
              删除
            </NButton>
          )
        }}
      </NPopconfirm>
    </div>
  );
};

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');

function handleAdd() {
  operateType.value = 'add';
  openModal();
}

async function handleBatchDelete() {
  const { error } = await fetchBatchDeleteMenu(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

function handleDelete(id: number) {
  onDeleted();
}

const editingData: Ref<Api.SystemManage.Menu | null> = ref(null);

async function handleEdit(item: Api.SystemManage.Menu) {
  const { data: detail } = await fetchGetMenuDetail(item.id);
  operateType.value = 'edit';
  editingData.value = detail;
  openModal();
}

function handleAddChildMenu(item: Api.SystemManage.Menu) {
  operateType.value = 'addChild';
  editingData.value = { ...item };
  openModal();
}

const allPages = ref<string[]>([]);

async function getAllPages() {
  const { data: pages } = await fetchGetAllPages();
  allPages.value = pages || [];
}

function init() {
  getTreeData();
  getAllPages();
}

init();
</script>

<template>
  <div ref="wrapperRef" class="h-full flex overflow-hidden">
    <div class="h-full w-1/4 overflow-hidden pr-2">
      <NCard title="菜单" :bordered="false" size="small" class="h-full overflow-hidden">
        <div class="p-2">
          <NInput v-model:value="searchKeyword" placeholder="搜索菜单" clearable>
            <template #prefix>
              <icon-ic-outline-search class="text-icon" />
            </template>
          </NInput>
        </div>
        <NTree
          block-line
          :data="treeData"
          :expanded-keys="expandedKeys"
          :selected-keys="selectedKeys"
          :on-update:expanded-keys="keys => (expandedKeys = keys)"
          :on-update:selected-keys="
            keys => {
              // 只有当keys变化时才刷新表格
              if (JSON.stringify(keys) !== JSON.stringify(selectedKeys)) {
                selectedKeys = keys;
                if (keys.length > 0) {
                  searchParams.parentId = Number(keys[0]);
                } else {
                  searchParams.parentId = null;
                }
                getData();
              }
            }
          "
          :render-prefix="renderPrefix"
          :render-suffix="renderSuffix"
          :pattern="searchKeyword"
          class="h-full"
        />
      </NCard>
    </div>
    <div class="h-full w-3/4 overflow-hidden pl-2">
      <NCard title="权限管理" :bordered="false" size="small" class="h-full overflow-hidden card-wrapper">
        <template #header-extra>
          <TableHeaderOperation
            v-model:columns="columnChecks"
            :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading"
            @refresh="getData"
          >
            <template #prefix>
              <NButton size="small" ghost type="primary" @click="handleAdd">
                <template #icon>
                  <icon-ic-round-plus class="text-icon" />
                </template>
                {{ $t('common.add') }}
              </NButton>
              <NPopconfirm @positive-click="handleBatchDelete">
                <template #trigger>
                  <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                    <template #icon>
                      <icon-ic-round-delete class="text-icon" />
                    </template>
                    {{ $t('common.batchDelete') }}
                  </NButton>
                </template>
                {{ $t('common.confirmDelete') }}
              </NPopconfirm>
            </template>
          </TableHeaderOperation>
        </template>
        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :flex-height="!appStore.isMobile"
          :scroll-x="1088"
          :loading="loading"
          :row-key="row => row.id"
          remote
          :pagination="pagination"
          class="sm:h-full"
        />
        <MenuOperateModal
          v-model:visible="visible"
          :operate-type="operateType"
          :row-data="editingData"
          :all-pages="allPages"
          @submitted="getDataByPage"
        />
      </NCard>
    </div>
  </div>
</template>

<style scoped></style>
